package org.firebug.spring.boot.validator.handler;

import org.firebug.common.core.api.Meta;
import org.firebug.common.core.api.Response;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 */
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * jsr303参数验证失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response validExceptionHandler(MethodArgumentNotValidException e){
        Map<String, String> error = new HashMap<>();
        Errors errors = e.getBindingResult();
        if (errors.hasErrors()) {
            for (FieldError field : errors.getFieldErrors()) {
                error.put(field.getField(), field.getDefaultMessage());
            }
        }
        return Response.ng(Meta._400, error);
    }
}
